package com.pojoin.system.service.impl;

import com.pojoin.common.Constant;
import com.pojoin.common.config.JdoConfig;
import com.pojoin.common.domain.FileDO;
import com.pojoin.common.domain.Tree;
import com.pojoin.common.service.FileService;
import com.pojoin.common.utils.*;
import com.pojoin.system.dao.*;
import com.pojoin.system.domain.*;
import com.pojoin.system.service.FinanceService;
import com.pojoin.system.service.MoneyHistoryService;
import com.pojoin.system.service.ShopuserService;
import com.pojoin.system.service.UserService;
import com.pojoin.system.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//@CacheConfig(cacheNames = "user")
//@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userMapper;
    @Autowired
    UserRoleDao userRoleMapper;
    @Autowired
    DeptDao deptMapper;
    @Autowired
    private FileService sysFileService;
    @Autowired
    private JdoConfig jdoConfig;
    @Autowired
    private ShopuserService shopuserService;
    @Autowired
    private MoneyHistoryService moneyHistoryService;
    @Autowired
    UserDao userDao;


    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Override
//    @Cacheable(key = "#id")
    public UserDO get(Long id) {
        List<Long> roleIds = userRoleMapper.listRoleId(id);
        UserDO user = userMapper.get(id);
        user.setDeptName(deptMapper.get(user.getDeptId()).getName());
        user.setRoleIds(roleIds);
        return user;
    }

    @Override
    public UserDO getByCode(String code) {
        return userMapper.getByCore(code);
    }

    @Override
    public List<UserDO> list(Map<String, Object> map) {
        return userMapper.list(map);
    }

    @Override
    public List<UserDO> partners(Map<String, Object> map) {
        List<UserDO> listH = userDao.listH(map);
        return listH;
    }

    @Override
    public int count(Map<String, Object> map) {
        return userMapper.count(map);
    }

    @Override
    public int countPartner(Map<String, Object> map) {
        return userMapper.countPartner(map);
    }

    // 升级合伙人
    private boolean partner() {
        Map map = new HashMap<>(1);
        //拿到所有的五星
        List<UserDO> list = userMapper.listAllGradeLgFive();
        // 拿到所有的合伙人
        /*map.put("partner", Constant.PARTNER);
        List<UserDO> list1 = userMapper.listAll(map);*/
        /*map.put("grade", "董事");
        List<UserDO> list2 = userMapper.listAll(map);*/
        /*if (list1 != null && list1.size() > 0) {
            list.addAll(list1);
        }*/
        /*if (list2 != null && list2.size() > 0) {
            list.addAll(list2);
        }*/
        if (list.size() > 0) {
            aa(list, "合伙人");
            return true;
        }
        return false;
    }

    private void aa(List<UserDO> list, String role) {
        for (UserDO userDO : list) {
            Long userId = userDO.getUserId();
            if(userId == 87994L || userId==94397L){

            }
            Set<UserDO> userDOList = new HashSet<>();
            for (UserDO aDo : list) {
                if (userId.equals(aDo.getParentId())) {
                    userDOList.add(aDo);
                }
                continue;
            }
            if (userDOList.size() >= 2) {
                // 升级为合伙人
                // userDO.setGrade(role);
                userDO.setPartner(Constant.PARTNER);
                userMapper.update(userDO);
            }
            continue;
            /*Map map1=new HashMap();
            map1.put("parentId", userDO.getUserId());
            List<UserDO> userDOS=userMapper.list(map1);
            if (userDOS.size()>=2){
                userDO.setGrade(role);
                userMapper.update(userDO);
            }
            continue;*/
        }
    }

    private void insertDirector(Long userId, DeptDO deptDO, UserDO session, String xing, Integer fiveNumber) throws Exception {
        //user.setGrade(director);
        //gradeDO.setGradeName(director);
        //成为合伙人的条件为其子类必须有两个五星
        UserDO xuserDo = new UserDO();
        xuserDo.setBalance(0d);
        xuserDo.setParentId(userId);
        xuserDo.setDeptId(deptDO.getDeptId());
        xuserDo.setStatus(8);
        xuserDo.setGrade(xing);
        DateFormat dateFormatformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormatformat.format(new Date());
        xuserDo.setUsername(format);
        xuserDo.setName(format);
        xuserDo.setInvitateCode(session.getUsername());
        xuserDo.setParentLink(session.getParentLink() + "," + session.getUserId());
        userMapper.save(xuserDo);
        Thread.sleep(10);
        UserDO oneDo = new UserDO();
        oneDo.setBalance(0d);
        oneDo.setParentId(userId);
        oneDo.setDeptId(deptDO.getDeptId());
        oneDo.setStatus(8);
        oneDo.setGrade(xing);
        String oneformat = dateFormatformat.format(new Date());
        oneDo.setUsername(oneformat);
        oneDo.setName(format);
        oneDo.setInvitateCode(session.getUsername());
        oneDo.setParentLink(session.getParentLink() + "," + session.getUserId());
        userMapper.save(oneDo);
        DeptDO dept = isDept(xuserDo);
        DeptDO dept1 = isDept(oneDo);
        insertUsers(fiveNumber, xuserDo, xuserDo.getUserId(), dept);
        insertUsers(fiveNumber, oneDo, oneDo.getUserId(), dept1);
    }

    private void director() {
        Map map = new HashMap<>();
        map.put("grade", "合伙人");
        //拿到所有的合伙人
        List<UserDO> list = userMapper.listAll(map);
        map.put("grade", "董事");
        List<UserDO> list2 = userMapper.listAll(map);
        if (list2 != null && list2.size() > 0) {
            list.addAll(list2);
        }
        if (list.size() == 0)
            return;
        aa(list, "董事");
    }

    private void getGrade(UserDO userDO) {
        //星级表
        List<GradeDO> list = gradeDao.list(new HashMap<>());
        List<UserDO> userDOS = userMapper.listInvite(userDO.getParentLink() + "," + userDO.getUserId());
        System.out.println(userDO.getParentLink() + "," + userDO.getUserId());
        for (GradeDO gradeDO : list) {
            if ("一代".equals(gradeDO.getGradeName()) || "二代".equals(gradeDO.getGradeName())) {
                continue;
            }
            for (UserDO aDo : userDOS) {
                int i = userMapper.countMyTeam(aDo.getUserId());
                aDo = userMapper.get(aDo.getUserId());
                aDo.setNum(i++);
                if (aDo.getNum() >= gradeDO.getNumber()) {
                    aDo.setGrade(gradeDO.getGradeName());
                }
                userMapper.update(aDo);
            }
        }
    }

    @Autowired
    FinanceService financeService;

    private DeptDO isDept(UserDO userDO) {
        DeptDO deptDO = new DeptDO();
        Map map = new HashMap();
        map.put("name", userDO.getName());
        //判断该邀请商是否是第一次邀请到商家
        List<DeptDO> depts = deptMapper.list(map);
        if (depts.size() >= 1) {
            deptDO = depts.get(0);
        } else {
            deptDO.setParentId(userDO.getDeptId());
            deptDO.setDelFlag(1);
            deptDO.setOrderNum(1);
            deptDO.setName(userDO.getName());
            deptMapper.save(deptDO);
        }
        return deptDO;
    }

    /**
     * 保存会员
     *
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int save(UserDO user) {
        boolean isShop=user.getLevel().equals("0")?true:false;
        int count = 0;
        //判断是否有重复code
        UserDO quser = userMapper.selectByCode(user.getCode());
        //判断是否有正确的报单中心
        UserDO userDO = userMapper.selectByCode(user.getCoreCode());
        //判断推荐人是否存在
        UserDO inviteCode = userMapper.selectByCode(user.getInvitateCode());
        Double money = 0d;
        // 如果是商家
        if (quser == null) {
            if (userDO != null && inviteCode != null && !"0".equals(userDO.getLevel())) {
                //financeService.core(user.getUserId(), money);
                //DeptDO deptDO=new DeptDO();
                DeptDO deptDO = isDept(inviteCode);
               /* Map map=new HashMap();
                map.put("name", inviteCode.getName());
                //判断该邀请商是否是第一次邀请到商家
                List<DeptDO> depts = deptMapper.list(map);
                if (depts.size()>=1){
                    deptDO = depts.get(0);
                }else {
                    deptDO.setParentId(inviteCode.getDeptId());
                    deptDO.setDelFlag(1);
                    deptDO.setOrderNum(1);
                    deptDO.setName(inviteCode.getName());
                    deptMapper.save(deptDO);
                }*/
                user.setBalance(0.0);
                user.setStatus(1);
                user.setGrade("无");
                user.setDeptId(deptDO.getDeptId());
                user.setParentId(inviteCode.getUserId());
                user.setParentLink(inviteCode.getParentLink() + "," + inviteCode.getUserId());
                OrderDO orderDO = new OrderDO();
                orderDO.setCreatTime(new Date());
                String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) (Math.random() * 90000 + 10000);
                orderDO.setOrderNumber(outTradeNo);
                orderDO.setStatus("1");
                orderDO.setToUsername(userDO.getName());
                orderDO.setFromUsername(user.getName());
                if ("0".equals(user.getLevel())) {
                    user.setRoleIds(Arrays.asList(63L));
                    if (userDO.getBalance() >= 365) {
                        userDO.setBalance(userDO.getBalance() - 365);
                        orderDO.setMoney(365.0);
                        money = 365d;

                    } else {
                        count = 1 / 0;
                    }
                } else {
                    user.setRoleIds(Arrays.asList(62L));
                    // 二级代理
                    if ("1".equals(user.getLevel())) {
                        if (userDO.getBalance() >= 3650) {
                            orderDO.setMoney(3650d);
                            userDO.setBalance(userDO.getBalance() - 3650);
                            money = 3650d;
                        } else {
                            count = 1 / 0;
                        }
                    // 一级代理
                    } else if ("2".equals(user.getLevel())) {
                        if (userDO.getBalance() >= 36500) {
                            userDO.setBalance(userDO.getBalance() - 36500);
                            orderDO.setMoney(36500.0);
                            money = 36500d;
                        } else {
                            count = 1 / 0;
                        }
                    } else {
                        if (userDO.getBalance() >= 100000) {
                            userDO.setBalance(userDO.getBalance() - 100000);
                            orderDO.setMoney(100000.0);
                            money = 100000.0d;
                        } else {
                            count = 1 / 0;
                        }
                    }
                }
                user.setUsername(user.getCode());
                user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
                user.setDeptId(deptDO.getDeptId());
                count = userMapper.save(user);
                userMapper.update(userDO);
                if(isShop){
                    financeService.core(user, inviteCode, userDO, user.getUserId(), money);
                }
                inviteCode = userMapper.get(inviteCode.getUserId());
                Long userId = user.getUserId();
                userDO = userMapper.get(userDO.getUserId());
                DeptDO dept = isDept(inviteCode);
                List<GradeDO> gradeDOS = gradeDao.list(new HashMap<>(16));
                int invitecount = userMapper.countMyTeam(inviteCode.getUserId());

                if ("1".equals(user.getLevel())) {
                    invitecount = invitecount + 10;
                    for (GradeDO aDo : gradeDOS) {
                        if ("一代".equals(aDo.getGradeName()) || "二代".equals(aDo.getGradeName())) {
                            continue;
                        }

                        if (invitecount >= aDo.getNumber()) {
                            inviteCode.setGrade(aDo.getGradeName());
                        }
                    }
                    insertUsers(9, inviteCode, inviteCode.getUserId(), dept);
                } else if ("2".equals(user.getLevel())) {
                    invitecount = invitecount + 100;
                    for (GradeDO aDo : gradeDOS) {
                        if ("一代".equals(aDo.getGradeName()) || "二代".equals(aDo.getGradeName())) {
                            continue;
                        }
                        if (invitecount >= aDo.getNumber()) {
                            inviteCode.setGrade(aDo.getGradeName());
                        }
                    }

                    insertUsers(99, inviteCode, inviteCode.getUserId(), dept);
                }
                userMapper.update(inviteCode);
                orderDO.setUserId((int) (long) userId);
                orderDao.save(orderDO);
                /*记账*/
                UserDO moneyUser=userMapper.get(Long.valueOf(userDO.getUserId()));
                moneyHistoryService.addMoney(Long.valueOf(userDO.getUserId()),0d, -orderDO.getMoney(), user.getUserId(),"注册","b",String.valueOf(moneyUser.getMoney()),String.valueOf(moneyUser.getBalance()));
                List<Long> roles = user.getRoleIds();
                userRoleMapper.removeByUserId(userId);
                List<UserRoleDO> list = new ArrayList<>();

                addRole(roles, userId, list);
                if (list.size() > 0) {
                    userRoleMapper.batchSave(list);
                }
                // 升级星级
                getGrade(inviteCode);

                partner();
                    // director();
            } else {
                //该用户不是报单中心
                return 7;
            }
            // financeService.core(user.getUserId(), money);
        } else {
            //编号已存在
            return 5;
        }
        if(!isShop){
            financeService.core(user, inviteCode, userDO, user.getUserId(), money);
        }
        /*保存app用户*/
//        int i= shopuserService.save(user);
//        if (i == 0) {
//            return 1;
//        }else if(i==2){
//           return 2;
//        } else{
//            return 500;
//        }
        return count;

    }

    @Override
    @Transactional
    public int updateUserLevel(UserDO userDO, UserDO user, UserDO session) throws Exception {
        //userDo 为当前登录的保单中心 session 为原来对象 user为用户新修改的对象
        userDO = userMapper.get(userDO.getUserId());
        List<Long> roles = new ArrayList<>();
        List<UserRoleDO> list = new ArrayList<>();
        int count = 0;
        int level = Integer.parseInt(session.getLevel());
        System.out.println(level);
        int userLevel = Integer.parseInt(user.getLevel());
        System.out.println(userLevel);
        // todo userId 就是 session 用户 ID
        Long userId = session.getUserId();
        if (-1 == userLevel) {
            //返回-1说明没有选择会员级别
            //throw new RuntimeException("请选择正确的会员级别");
            return -1;
        }

        user.setUserId(session.getUserId());
        List<Long> roleIds = new ArrayList<>();

        //如果相等,说明是普通修改,与钱无关
        GradeDO gradeDO = gradeDao.get(Integer.parseInt(user.getGrade()));
        //五星的数量
        Integer fiveNumber = gradeDao.get(Constant.GRADE_5).getNumber();
        if (gradeDO == null) {
            gradeDO = new GradeDO();
            gradeDO.setNumber(0);
            if ("-1".equals(user.getGrade())) {
                gradeDO.setGradeName("无");
            }

        }

        if (userLevel == level && session.getGrade().equals(gradeDO.getGradeName())) {
            user.setGrade(session.getGrade());
            int update = userMapper.update(user);
            partner();
            return update;
        } else {
            UserRoleDO roleId = userRoleMapper.getRoleId(userDO.getUserId());
            //user.setGrade(session.getGrade());
            roleIds.add(roleId.getRoleId());
            if (roleIds.contains(61l)) {
                // todo 判断修改是否为合伙人或者董事  这里改为升级是判断 是否是合伙人
                DeptDO deptDO = isDept(session);
                /*user = userMapper.get(user.getUserId());
                // 获取上线
                UserDO inviteUser = userMapper.selectByCode(user.getInvitateCode());
                getGrade(inviteUser);*/

                if ("600".equals(user.getGrade()) || "700".equals(user.getGrade())) {
                    if ("600".equals(user.getGrade())) {
                        //说明将星级修改为合伙人,程序走到这必然是刻意为之
                        //因此不必在意其底下到底有多少邀请人,直接升级到合伙人即可
                        becomePartner(user, session, userId, gradeDO, fiveNumber, deptDO);
                    }
                } else if (!session.getGrade().equals(gradeDO.getGradeName())) {
                    if (roleIds.contains(61l)) {
                        if ("-1".equals(user.getGrade())) {
                            user.setGrade("无");
                        } else {
                            user.setGrade(gradeDO.getGradeName()); // 更新用户星级
                        }
                        int i = userMapper.countMyTeam(userId);
                        i = gradeDO.getNumber() - i; // 用户升星所差的人数
                        if (i > 0) {
                            insertUsers(i, session, userId, deptDO);
                            // todo 更新父级邀请人数 星级 是否是合伙人
                            // 1. 查询父级列表
                            user = userMapper.get(userId);
                            // 更新用户邀请人数
                            user.setNum(gradeDO.getNumber());
                            if(user.getParentLink() != null){
                                // 星级列表
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("sort", "id");
                                map.put("order", "asc");
                                List<GradeDO> gradeList = gradeDao.list(map);
                                List<UserDO> userDOS = userMapper.listInvite(user.getParentLink());
                                for (UserDO aDo : userDOS) {
                                    aDo = userMapper.get(aDo.getUserId());
                                    int num = aDo.getNum() + i;
                                    aDo.setNum(num);
                                    // todo 更新星级错误
                                    for (GradeDO grade : gradeList) {

                                        if ("一代".equals(grade.getGradeName()) || "二代".equals(grade.getGradeName())) {
                                            continue;
                                        }
                                        if (aDo.getNum() < grade.getNumber()) {
                                            // 增加邀请人(这里增加的人  为自带手动升星人数)
                                            insertUsers(i, aDo, aDo.getUserId(), deptDO);
                                            break ;
                                        }
                                        aDo.setGrade(grade.getGradeName());
                                        // 更新父级星级
                                        userMapper.update(aDo);
                                    }

                                }





                            }
                        }
                    } else {
                        user.setGrade(session.getGrade());
                    }
                } else {
                    user.setGrade(gradeDO.getGradeName());
                }
            }


            double balance = 0d;
            //要修改等级 需扣除当前用户对应的Balance
            //先判断用户修改的level是否等于0 理论上不可能等于1,防止万一
            roles = Arrays.asList(62l);
            //当修改之前
            Map map = getBalance(userLevel, level);
            Boolean msg = (Boolean) map.get("msg");
            balance = (Double) map.get("balance");
            if (msg) {
                if (userDO.getBalance() >= balance) {
                    addRole(roles, userId, list);
                    if (list.size() > 0) {
                        userRoleMapper.removeByUserId(userId);
                        userRoleMapper.batchSave(list);
                    }
                    if (balance >= 60000) {
                        userMapper.updateBalance(balance, userId);
                    }
                    OrderDO orderDO = new OrderDO();
                    String outTradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) (Math.random() * 90000 + 10000);
                    orderDO.setOrderNumber(outTradeNo);
                    orderDO.setMoney(balance);
                    orderDO.setUserId((int) (long) userId);
                    orderDO.setFromUsername(session.getName());
                    orderDO.setToUsername(userDO.getName());
                    orderDO.setStatus("1");
                    orderDO.setCreatTime(new Date());
                    orderDao.save(orderDO);
                    if ("-1".equals(user.getGrade())) {
                        user.setGrade("无");
                    }//else {
                    //   user.setGrade(session.getGrade());
                    //}
                    userMapper.update(user);
                    // todo 升级合伙人逻辑
                    partner();
                    user=userMapper.get(user.getUserId());
                    //修改app用户
                    updateAppAgentUser(user,session);
                    return userMapper.updateBalance(-balance, userDO.getUserId());
                } else {
                    //throw new RuntimeException("自己有多少币没有点B数吗");
                    return 2;
                }
            } else {
                //throw new RuntimeException("系统不支持会员降级");
                if (!gradeDO.getGradeName().equals(session.getGrade())) {
                    if (roleIds.contains(61l)) {
                        user.setGrade(gradeDO.getGradeName());
                        userMapper.update(user);
                        partner();
                        user=userMapper.get(user.getUserId());
                        //修改app用户
                        updateAppAgentUser(user,session);
                        return 1;
                    } else {
                        return 1 / 0;
                    }
                }
                return 3;
            }
        }
    }

    private void becomePartner(UserDO user, UserDO session, Long userId, GradeDO gradeDO, Integer fiveNumber, DeptDO deptDO) throws InterruptedException {
        user.setGrade("合伙人");
        gradeDO.setGradeName("合伙人");
        //成为合伙人的条件为其子类必须有两个五星
        UserDO xuserDo = new UserDO();
        xuserDo.setBalance(0d);
        xuserDo.setParentId(userId);
        xuserDo.setDeptId(deptDO.getDeptId());
        xuserDo.setStatus(8);
        xuserDo.setGrade("五星");
        DateFormat dateFormatformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormatformat.format(new Date());
        xuserDo.setUsername(format);
        xuserDo.setName(format);
        xuserDo.setInvitateCode(session.getUsername());
        xuserDo.setParentLink(session.getParentLink() + "," + session.getUserId());
        userMapper.save(xuserDo);
        Thread.sleep(10);
        UserDO oneDo = new UserDO();
        oneDo.setBalance(0d);
        oneDo.setParentId(userId);
        oneDo.setDeptId(deptDO.getDeptId());
        oneDo.setStatus(8);
        oneDo.setGrade("五星");
        String oneformat = dateFormatformat.format(new Date());
        oneDo.setUsername(oneformat);
        oneDo.setName(format);
        oneDo.setInvitateCode(session.getUsername());
        oneDo.setParentLink(session.getParentLink() + "," + session.getUserId());
        userMapper.save(oneDo);
        DeptDO dept = isDept(xuserDo);
        DeptDO dept1 = isDept(oneDo);
        insertUsers(fiveNumber, xuserDo, xuserDo.getUserId(), dept);
        insertUsers(fiveNumber, oneDo, oneDo.getUserId(), dept1);
    }

    private Map getBalance(int userLevel, int level) {
        double balance = 0d;
        boolean msg = true;
        Map map = new HashMap();
        if (userLevel > level && level == 0) {
            switch (userLevel) {
                case 1:
                    balance = 3650 - 365;
                    break;
                case 2:
                    balance = 36500 - 365;
                    break;
                case 3:
                    balance = 100000 - 365;
                    break;
            }
            msg = true;
        } else if (userLevel > level && level == 1) {
            switch (userLevel) {
                case 2:
                    balance = 36500 - 3650;
                    break;
                case 3:
                    balance = 100000 - 3650;
                    break;
            }
            msg = true;
        } else if (userLevel > level && level == 2) {
            switch (userLevel) {
                case 3:
                    balance = 100000 - 36500;
                    break;
            }
            msg = true;
        } else {
            msg = false;
        }
        map.put("msg", msg);
        map.put("balance", balance);
        return map;
    }

    private void sendMoney(UserDO inviteUser, UserDO userDO, Double sendMoney) {
        logger.info("分润开始 报单中心拿金额的5%");
        userDO.setMoney(sendMoney * 0.05);
        //邀请人的星级
        String grade = inviteUser.getGrade();
        //邀请人团队的总人数
        List<UserDO> grade1 = new ArrayList<>();
        List<UserDO> grade2 = new ArrayList<>();
        List<UserDO> grade3 = new ArrayList<>();
        List<UserDO> grade4 = new ArrayList<>();
        List<UserDO> grade5 = new ArrayList<>();
        List<UserDO> gradeh = new ArrayList<>();
        List<UserDO> graded = new ArrayList<>();
        List<UserDO> list = userMapper.listInvite(inviteUser.getParentLink());
        for (UserDO aDo : list) {
            if ("一星".equals(aDo.getGrade())) {
                grade1.add(aDo);
                continue;
            }
            if ("二星".equals(aDo.getGrade())) {
                grade2.add(aDo);
                continue;
            }
            if ("三星".equals(aDo.getGrade())) {
                grade3.add(aDo);
                continue;
            }
            if ("四星".equals(aDo.getGrade())) {
                grade4.add(aDo);
                continue;
            }
            if ("五星".equals(aDo.getGrade())) {
                grade5.add(aDo);
                continue;
            }
            if ("合伙人".equals(aDo.getGrade())) {
                gradeh.add(aDo);
                continue;
            }
            if ("董事".equals(aDo.getGrade())) {
                graded.add(aDo);
                continue;
            }
            //邀请人的初始分成为15%
            double money = 0.15;
            double money1 = 0.0;
            double money2 = 0.0;
            double money3 = 0.0;
            double money4 = 0.0;
            double money5 = 0.0;
            double moneyh = 0.0;
            double moneyd = 0.0;
            //星星的利润值
            double gradeMmoney1 = 0.0;
            double gradeMmoney2 = 0.0;
            double gradeMmoney3 = 0.0;
            double gradeMmoney4 = 0.0;
            double gradeMmoney5 = 0.0;
            double gradeMmoneyOne = 0.0;
            double gradeMmoneyTwo = 0.0;
            List<GradeDO> gradeDOList = gradeDao.list(new HashMap<>(16));
            for (GradeDO gradeDO : gradeDOList) {
                if ("一星".equals(gradeDO.getGradeName())) {
                    gradeMmoney1 = gradeDO.getProportion();
                }
                if ("二星".equals(gradeDO.getGradeName())) {
                    gradeMmoney2 = gradeDO.getProportion();
                }
                if ("三星".equals(gradeDO.getGradeName())) {
                    gradeMmoney3 = gradeDO.getProportion();
                }
                if ("四星".equals(gradeDO.getGradeName())) {
                    gradeMmoney4 = gradeDO.getProportion();
                }
                if ("五星".equals(gradeDO.getGradeName())) {
                    gradeMmoney5 = gradeDO.getProportion();
                }
                if ("一代".equals(gradeDO.getGradeName())) {
                    gradeMmoneyOne = gradeDO.getProportion();
                }
                if ("二代".equals(gradeDO.getGradeName())) {
                    gradeMmoneyTwo = gradeDO.getProportion();
                }
            }
            if ("无".equals(grade)) {
                money = 0.15;
                if (grade1.size() > 0 && grade2.size() > 0 && grade3.size() > 0 && grade4.size() > 0 && grade5.size() > 0 && gradeh.size() > 0 && graded.size() > 0) {
                    money1 = gradeMmoney1;
                    money2 = gradeMmoney2 - money1;
                    money3 = gradeMmoney3 - gradeMmoney2;
                    money4 = gradeMmoney4 - gradeMmoney3;
                    money5 = gradeMmoney5 - gradeMmoney4;
                }
            }


        }
    }

    @Resource(name = "sqlSessionTemplate")
    private SqlSessionTemplate sqlSessionTemplate;

    public SqlSessionTemplate getSqlSessionTemplate()
    {
        return sqlSessionTemplate;
    }
    private void insertUsers(int i, UserDO session, long userId, DeptDO deptDO) {

        List<UserDO> members = new ArrayList<>(1000);
        for (int b = 1; b <= i; b++) {
            UserDO xuserDo = prepareInsertData(i, session, userId, deptDO);
            members.add(xuserDo);
            // userMapper.save(xuserDo);
        }

        int result = 1;
        SqlSession sqlSession = null;
        try {
            sqlSession = this.getSqlSessionTemplate()
                    .getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
            int batchCount = 1000;// 每批commit的个数
            int batchLastIndex = batchCount;// 每批最后一个的下标
            for (int index = 0; index < i;) {
                if (batchLastIndex >= i) {
                    batchLastIndex = i;
                    result = result * sqlSession.insert("com.pojoin.system.dao.UserDao.insertData",members.subList(index, batchLastIndex));
                    sqlSession.commit();
                    System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                    break;// 数据插入完毕，退出循环
                } else {
                    result = result * sqlSession.insert("com.pojoin.system.dao.UserDao.insertData",members.subList(index, batchLastIndex));
                    sqlSession.commit();
                    System.out.println("index:" + index+ " batchLastIndex:" + batchLastIndex);
                    index = batchLastIndex;// 设置下一批下标
                    batchLastIndex = index + (batchCount - 1);
                }
            }
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
            throw new RuntimeException("保存数据异常",e);
        }finally {
            if (sqlSession != null) {
                sqlSession.close();
            }

        }


    }

    private void insertUsers2(int i, UserDO session, long userId, DeptDO deptDO) {
        for (int b = 1; b <= i; b++) {
            UserDO xuserDo = new UserDO();
            xuserDo.setBalance(0d);
            xuserDo.setParentId(userId);
            xuserDo.setDeptId(deptDO.getDeptId());
            xuserDo.setStatus(8);
            xuserDo.setGrade("无");
            String s = UUID.randomUUID().toString();
            xuserDo.setUsername(s + i);
            xuserDo.setName(s + i);
            xuserDo.setInvitateCode(session.getUsername());
            xuserDo.setParentLink(session.getParentLink() + "," + session.getUserId());
            userMapper.save(xuserDo);
        }
    }

    private UserDO prepareInsertData(int i, UserDO session, long userId, DeptDO deptDO) {
        UserDO xuserDo = new UserDO();
        xuserDo.setBalance(0d);
        xuserDo.setParentId(userId);
        xuserDo.setDeptId(deptDO.getDeptId());
        xuserDo.setStatus(8);
        xuserDo.setGrade("无");
        String s = UUID.randomUUID().toString();
        xuserDo.setUsername(s + i);
        xuserDo.setName(s + i);
        xuserDo.setInvitateCode(session.getUsername());
        xuserDo.setParentLink(session.getParentLink() + "," + session.getUserId());
        return xuserDo;
    }

    //@Test
    public void getS() {
        Long aa = 164L;
        Long bb = 164L;
        System.out.println(aa.equals(bb));
    }

    private void addRole(List<Long> roles, Long userId, List<UserRoleDO> list) {
        for (Long roleId : roles) {
            UserRoleDO ur = new UserRoleDO();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
    }

    @Override
    public int update(UserDO user) {
        int r = userMapper.update(user);
        Long userId = user.getUserId();
        List<Long> roles = user.getRoleIds();
        userRoleMapper.removeByUserId(userId);
        List<UserRoleDO> list = new ArrayList<>();
        /*for (Long roleId : roles) {
            UserRoleDO ur = new UserRoleDO();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }*/
        addRole(roles, userId, list);
        if (list.size() > 0) {
            userRoleMapper.batchSave(list);
        }
        return r;
    }

    @Override
    public int remove(Long userId) {
        userRoleMapper.removeByUserId(userId);
        return userMapper.remove(userId);
    }

    @Override
    public boolean exit(Map<String, Object> params) {
        boolean exit;
        exit = userMapper.list(params).size() > 0;
        return exit;
    }

    @Override
    public Set<String> listRoles(Long userId) {
        return null;
    }

    @Override
    public int resetPwd(UserVO userVO, UserDO userDO) throws Exception {
        if (Objects.equals(userVO.getUserDO().getUserId(), userDO.getUserId())) {
            if (Objects.equals(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdOld()), userDO.getPassword())) {
                userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdNew()));
                return userMapper.update(userDO);
            } else {
                throw new Exception("输入的旧密码有误！");
            }
        } else {
            throw new Exception("你修改的不是你登录的账号！");
        }
    }

    @Override
    public int adminResetPwd(UserVO userVO) throws Exception {
        UserDO userDO = get(userVO.getUserDO().getUserId());
        if ("admin".equals(userDO.getUsername())) {
            throw new Exception("超级管理员的账号不允许直接重置！");
        }
        userDO.setPassword(MD5Utils.encrypt(userDO.getUsername(), userVO.getPwdNew()));
        return userMapper.update(userDO);


    }

    @Transactional
    @Override
    public int batchremove(Long[] userIds) {
        int count = userMapper.batchRemove(userIds);
        userRoleMapper.batchRemoveByUserId(userIds);
        return count;
    }

    @Override
    public Tree<UserDO> getTree(UserDO user) {
        /*List<Tree<DeptDO>> trees = new ArrayList<Tree<DeptDO>>();
        //获取当前角色及二代所有的部门
        user.getDeptId();
        Map map=new HashMap();
        map.put("parentId", user.getDeptId());
        List<DeptDO> depts = deptMapper.list(map);
        for (DeptDO dept : depts) {
            Map map1=new HashMap();
            map1.put("parentId", dept.getDeptId());
            List<DeptDO> deptss = deptMapper.list(map1);
            for (DeptDO deptDO : deptss) {
                depts.add(deptDO);
            }
        }
        //加上他自己
        depts.add(deptMapper.get(user.getDeptId()));
        //获取当前所有的角色deptid
        List<Long> deptids=new ArrayList<>();
        //获取所有的部门pid
        Long[] pDepts = deptMapper.listParentDept();
        //获取所有的用户的deptid
        Long[] uDepts = userMapper.listAllDept();
        //用户和部门所有的pid
        Long[] allDepts = (Long[]) ArrayUtils.addAll(pDepts, uDepts);
        for (DeptDO dept : depts) {
            deptids.add(dept.getDeptId());
            if (!ArrayUtils.contains(allDepts, dept.getDeptId())) {
                continue;
            }
            Tree<DeptDO> tree = new Tree<DeptDO>();
            tree.setId(dept.getDeptId().toString());
            tree.setParentId(dept.getParentId().toString());
            tree.setText(dept.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            state.put("mType", "dept");
            tree.setState(state);
            trees.add(tree);
        }
        //获取所有的用户
        List<UserDO> users = userMapper.list(new HashMap<String, Object>(16));
        for (UserDO user1 : users) {
            if (deptids.contains(user1.getDeptId())){
                System.out.println(user1.getDeptId());
                Tree<DeptDO> tree = new Tree<DeptDO>();
                tree.setId(user1.getUserId().toString());
                tree.setParentId(user1.getDeptId().toString());
                tree.setText(user1.getName());
                Map<String, Object> state = new HashMap<>(16);
                state.put("opened", true);
                state.put("mType", "user");
                tree.setState(state);
                trees.add(tree);
            }
            continue;
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<DeptDO> t = BuildTree.build(trees);
        return t;*/
        List<Tree<UserDO>> trees = new ArrayList<Tree<UserDO>>();

        List<UserDO> users = userMapper.list(new HashMap<String, Object>(16));
        for (UserDO user1 : users) {
            Tree<UserDO> tree = new Tree<UserDO>();
            tree.setId(user1.getUserId().toString());
            tree.setParentId(user1.getParentId().toString());
            if(user1.getUserId()== 25367L||user1.getUserId()== 27285L){
                tree.setText(user1.getName());
            }else{
                tree.setText(user1.getName() + " " + user1.getCode() + " " + user1.getGrade());
            }

            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<UserDO> t = BuildTree.build(trees, "149");
        return t;
    }

    @Override
    public int updatePersonal(UserDO userDO) {
        return userMapper.update(userDO);
    }

    @Override
    public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId) throws Exception {
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
        //获取图片后缀
        String prefix = fileName.substring((fileName.lastIndexOf(".") + 1));
        String[] str = avatar_data.split(",");
        //获取截取的x坐标
        int x = (int) Math.floor(Double.parseDouble(str[0].split(":")[1]));
        //获取截取的y坐标
        int y = (int) Math.floor(Double.parseDouble(str[1].split(":")[1]));
        //获取截取的高度
        int h = (int) Math.floor(Double.parseDouble(str[2].split(":")[1]));
        //获取截取的宽度
        int w = (int) Math.floor(Double.parseDouble(str[3].split(":")[1]));
        //获取旋转的角度
        int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));
        try {
            BufferedImage cutImage = ImageUtils.cutImage(file, x, y, w, h, prefix);
            BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean flag = ImageIO.write(rotateImage, prefix, out);
            //转换后存入数据库
            byte[] b = out.toByteArray();
            FileUtil.uploadFile(b, jdoConfig.getUploadPath(), fileName);
        } catch (Exception e) {
            throw new Exception("图片裁剪错误！！");
        }
        Map<String, Object> result = new HashMap<>();
        if (sysFileService.save(sysFile) > 0) {
            UserDO userDO = new UserDO();
            userDO.setUserId(userId);
            userDO.setPicId(sysFile.getId());
            if (userMapper.update(userDO) > 0) {
                result.put("url", sysFile.getUrl());
            }
        }
        return result;
    }

    @Override
    public String getnameBycode(String code) {
        UserDO userDO = userMapper.selectByCode(code);
        if (userDO != null) {
            if (StringUtils.isNotBlank(userDO.getName())) {
                return userDO.getName();
            }
        }
        return "没有找到该推荐人";
    }

    @Autowired
    private GradeDao gradeDao;

    @Override
    public List<GradeDO> findGradeList() {
        return gradeDao.list(new HashMap<>(16));
    }

    @Autowired
    private OrderDao orderDao;

    @Override
    public List<OrderDO> getOrderList(Query query) {
        return orderDao.list(query);
    }

    @Override
    public int getOrderCount(Query query) {
        return orderDao.count(query);
    }
    @Override
    @Transactional
    public String updateBalance(Integer id) {
        OrderDO orderDO = orderDao.get(id);
        if ("0".equals(orderDO.getStatus())) {
            Map map = new HashMap();
            map.put("userId", orderDO.getUserId());
            List<UserDO> list = userMapper.list(map);
            if (list.size() == 1) {
                UserDO userDO = list.get(0);
                userDO.setBalance(userDO.getBalance() + orderDO.getMoney());
                userMapper.update(userDO);
                orderDO.setStatus("1");
                orderDao.update(orderDO);
                moneyHistoryService.addMoney(userDO.getUserId(),0d,orderDO.getMoney(),1L,"拨币","b",userDO.getMoney()+"", userDO.getBalance() +"");
                return "拨币成功";
            }

        }
        return "拨币失败";
    }

    @Override
    public int countMyTeam(Long userId) {
        return userMapper.countMyTeam(userId);
    }

    @Override
    public int selectTodayNum() {
        return userMapper.selectTodayNum();
    }

    @Override
    public int selectSumUser() {
        return userMapper.selectSumUser();
    }

    @Override
    public int selectMemUserByLevel(String level) {
        return userMapper.selectMemUserByLevel(level);
    }

    @Override
    public int selectMemUserByGrade(String grade) {
        return userMapper.selectMemUserByGrade(grade);
    }

    @Override
    public Double selectSumMoney() {
        return userMapper.selectSumMoney();
    }

    private void getSs() {

    }
    //ShopagentuserDO代理商 省市代理
    //ShopchanneluserDO 渠道商 phone address userId
    //ShopDO 商家
    //ShopuserDO app用户
    @Autowired
    private ShopuserDao shopuserDao;
    @Autowired
    private ShopchanneluserDao shopchanneluserDao;
    @Autowired
    private ShopagentuserDao shopagentuserDao;

    private boolean updateAppAgentUser(UserDO user,UserDO session){
        String mobile = user.getMobile();//userDo中手机号和app用户对应
        ShopuserDO shopuser = shopuserDao.getByPhone(mobile);
        //修改
        if (shopuser!=null&&!"0".equals(user.getLevel())&&!user.getLevel().equals(session.getLevel())){

            if ("1".equals(user.getLevel())){
                ShopchanneluserDO shopchanneluserDO=new ShopchanneluserDO();
                shopchanneluserDO.setAddress(user.getLiveAddress());
                shopchanneluserDO.setUserid(shopuser.getId());
                shopchanneluserDO.setUsername(shopuser.getName());
                shopchanneluserDO.setPhone(mobile);
                shopchanneluserDO.setCreatetime(new Date());
                shopchanneluserDO.setInvitecode(shopuser.getInvitecode());
                shopchanneluserDao.save(shopchanneluserDO);
                shopuser.setIsagent(0);
                shopuserDao.update(shopuser);
                return true;
            }else {
                ShopchanneluserDO shopchanneluserDO=shopchanneluserDao.getChannelUserByPhone(mobile);
                if (shopchanneluserDO!=null){
                    shopchanneluserDao.remove(shopchanneluserDO.getId());
                }
                shopuser.setIsagent(1);
                ShopagentuserDO shopagentuserDO=new ShopagentuserDO();
                shopagentuserDO.setUserid(shopuser.getId());
                shopagentuserDO.setPhone(mobile);
                shopagentuserDO.setCreatetime(new Date());
                shopagentuserDO.setCompany(user.getName());
                shopagentuserDO.setInvitecode(shopuser.getInvitecode());
                if ("2".equals(user.getLevel())){
                    shopagentuserDO.setAgenttype("区/县代理商");
                    shopuser.setAgenttype("区/县代理商");
                }
                if ("3".equals(user.getLevel())){
                    shopagentuserDO.setAgenttype("市代理商");
                    shopuser.setAgenttype("市代理商");
                }
                shopagentuserDao.save(shopagentuserDO);
                shopuserDao.update(shopuser);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String pwd= MD5Utils.encrypt("12345", "11111");
        String pwd1 = MD5Utils.encrypt("13131808726", "11111");
        String pwd2 = MD5Utils.encrypt("15503183628", "111111");
        String shouhou=MD5Utils.encrypt("houtai","111111");
        System.out.println(pwd);
        System.out.println(pwd1);
        System.out.println(pwd2);
        System.out.println(shouhou);
    }
}
